package com.example.competition_1.services;

import com.example.competition_1.models.entity.*;
import gaarason.database.contract.eloquent.Record;
import gaarason.database.contract.eloquent.RecordList;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class UserWorkService {

    private final Work.Model workModel;
    private final WorkUser.Model workUserModel;
    private final Competitions.Model competitionsModel;

    private final AwardWorkCompetition.Model awardWorkCompetitionModel;

    private final Award.Model awardModel;


    public UserWorkService(Work.Model workModel, WorkUser.Model workUserModel, Competitions.Model competitionsModel, AwardWorkCompetition.Model awardWorkCompetitionModel, Award.Model awardModel) {
        this.workModel = workModel;
        this.workUserModel = workUserModel;
        this.competitionsModel = competitionsModel;
        this.awardWorkCompetitionModel = awardWorkCompetitionModel;
        this.awardModel = awardModel;
    }

    public List<Map<String, Object>> getWorksByUserId(String userId) {
        System.out.println("开始执行 getWorksByUserId 方法，传入的 userId 为: " + userId);

        List<Map<String, Object>> resultList = new ArrayList<>();

        System.out.println("开始根据 userId 查询对应的 workId 列表...");
        // 根据 userId 在 work_user 表中查找对应的 workId
        RecordList<WorkUser, ?> workUserRecords = workUserModel.newQuery()
                .where("userId", userId)
                .get();
        List<String> workIds = workUserRecords.stream()
                .map(Record::getEntity)
                .map(WorkUser::getWorkid)
                .collect(Collectors.toList());
        System.out.println("查询到的 workId 数量: " + workIds.size());

        if (workIds.isEmpty()) {
            System.out.println("未查询到对应的 workId，返回空结果");
            return resultList;
        }

        for (String workId : workIds) {
            System.out.println("开始处理 workId 为 " + workId + " 的作品");

            System.out.println("开始查询 work 表获取作品详细信息...");
            // 根据 workId 在 work 表中查询 work 信息
            RecordList<Work, ?> workRecords = workModel.newQuery()
                    .where("workId", workId)
                    .get();
            List<Work> works = workRecords.stream()
                    .map(Record::getEntity)
                    .collect(Collectors.toList());
            System.out.println("查询到的作品详细信息数量: " + works.size());

            for (Work work : works) {
                String competitionId = work.getCompetitionid();

                System.out.println("开始查询该作品的参与者列表...");
                // 查询该作品的参与者列表
                List<WorkUser> workUsers = workUserModel.newQuery()
                        .where("workId", workId)
                        .get()
                        .toObjectList();
                System.out.println("查询到该作品的参与者数量: " + workUsers.size());

                System.out.println("开始查询该作品的奖项列表...");
                // 查询该作品的奖项列表
                List<String> awardIds = awardWorkCompetitionModel.newQuery()
                        .where("workId", workId)
                        .select("awardId")
                        .get()
                        .stream()
                        .map(record -> record.getEntity().getAwardid())
                        .collect(Collectors.toList());
                List<Award> awardsForWork = new ArrayList<>();
                if (!awardIds.isEmpty()) {
                    awardsForWork = awardModel.newQuery()
                            .whereIn("awardId", awardIds)
                            .get()
                            .toObjectList();
                }
                System.out.println("查询到该作品的奖项数量: " + awardsForWork.size());

                System.out.println("开始查询该作品对应的竞赛信息...");
                // 查询该作品对应的竞赛信息
                List<Competitions> competitionList = competitionsModel.newQuery()
                        .where("id", competitionId)
                        .get()
                        .toObjectList();
                System.out.println("查询到的竞赛信息数量: " + competitionList.size());

                Competitions competition = null;
                if (!competitionList.isEmpty()) {
                    competition = competitionList.get(0);
                }

                String competitionName = competition != null? competition.getName() : "";

                Map<String, Object> combinedData = new HashMap<>();
                combinedData.put("workId", work.getWorkid());
                combinedData.put("workName", work.getWorkname());
                combinedData.put("competitionId", work.getCompetitionid());
                combinedData.put("status", work.getStatus());
                combinedData.put("description", work.getDescription());
                combinedData.put("category", work.getCategory());
                combinedData.put("teachStack", work.getTeachstack());
                combinedData.put("date", work.getDate());
                // 平铺award表信息
                for (Award award : awardsForWork) {
                    combinedData.put("awardId", award.getAwarid());
                    combinedData.put("awardDescription", award.getDescription());
                    combinedData.put("awardPrize", award.getAwardprize());
                    combinedData.put("awardTime", award.getAwardtime());
                    combinedData.put("createAt", award.getCreateat());
                    combinedData.put("updateAt", award.getUpdateat());
                }
                combinedData.put("workUsers", workUsers);
                combinedData.put("competitionName", competitionName);

                resultList.add(combinedData);
                System.out.println("作品 " + work.getWorkid() + " 处理完成");
            }
        }

        System.out.println("getWorksByUserId 方法执行完毕，最终结果数量: " + resultList.size());
        return resultList;
    }

    public List<Map<String, Object>> getThreeYears(String competitionId) {
        System.out.println("开始执行 getThreeYears 方法，传入的 competitionId 为: " + competitionId);
        // 获取当前日期
        LocalDate currentDate = LocalDate.now();
        // 计算三年前的日期
        LocalDate threeYearsAgo = currentDate.minus(3, ChronoUnit.YEARS);

        List<Map<String, Object>> resultList = new ArrayList<>();

        System.out.println("开始查询符合条件的作品列表...");
        // 获取符合条件的 workId 列表
        List<String> workIds = awardWorkCompetitionModel.newQuery()
                .where("competitionId", competitionId)
                .select("workId")
                .get()
                .stream()
                .map(record -> record.getEntity().getWorkid())
                .collect(Collectors.toList());
        System.out.println("查询到的 workId 数量: " + workIds.size());

        List<Work> works = new ArrayList<>();
        if (!workIds.isEmpty()) {
            works = workModel.newQuery()
                    .select("workId", "competitionId", "date")
                    .whereIn("workId", workIds)
                    .where("date", ">", threeYearsAgo)
                    .get()
                    .toObjectList();
        } else {
            System.out.println("未查询到符合条件的 workId，返回空结果");
            return resultList;
        }
        System.out.println("查询到的作品数量: " + works.size());

        for (Work work : works) {
            System.out.println("开始处理作品，workId: " + work.getWorkid());
            String workId = work.getWorkid();
            String competitionIdFromWork = work.getCompetitionid();

            System.out.println("开始查询该作品的参与者列表...");
            List<WorkUser> workUsers = workUserModel.newQuery()
                    .where("workId", workId)
                    .get()
                    .toObjectList();
            System.out.println("查询到该作品的参与者数量: " + workUsers.size());

            System.out.println("开始查询该作品的奖项列表...");
            // 获取该作品的 awardId 列表
            List<String> awardIds = awardWorkCompetitionModel.newQuery()
                    .where("workId", workId)
                    .select("awardId")
                    .get()
                    .stream()
                    .map(record -> record.getEntity().getAwardid())
                    .collect(Collectors.toList());
            List<Award> awardsForWork = new ArrayList<>();
            if (!awardIds.isEmpty()) {
                awardsForWork = awardModel.newQuery()
                        .whereIn("awarId", awardIds)
                        .get()
                        .toObjectList();
            }
            System.out.println("查询到该作品的奖项数量: " + awardsForWork.size());

            System.out.println("开始查询该作品对应的竞赛信息...");
            List<Competitions> competitionList = competitionsModel.newQuery()
                    .where("id", competitionIdFromWork)
                    .get()
                    .toObjectList();
            System.out.println("查询到的竞赛信息数量: " + competitionList.size());

            Competitions competition = null;
            if (!competitionList.isEmpty()) {
                competition = competitionList.get(0);
            }

            String competitionName = competition != null? competition.getName() : "";

            Map<String, Object> combinedData = new HashMap<>();
            combinedData.put("workId", work.getWorkid());
            combinedData.put("workName", work.getWorkname());
            combinedData.put("competitionId", work.getCompetitionid());
            combinedData.put("status", work.getStatus());
            combinedData.put("description", work.getDescription());
            combinedData.put("category", work.getCategory());
            combinedData.put("teachStack", work.getTeachstack());
            combinedData.put("date", work.getDate());
            // 平铺award表信息
            for (Award award : awardsForWork) {
                combinedData.put("awardId", award.getAwarid());
                combinedData.put("awardDescription", award.getDescription());
                combinedData.put("awardPrize", award.getAwardprize());
                combinedData.put("awardTime", award.getAwardtime());
                combinedData.put("createAt", award.getCreateat());
                combinedData.put("updateAt", award.getUpdateat());
            }
            combinedData.put("workUsers", workUsers);
            combinedData.put("competitionName", competitionName);

            resultList.add(combinedData);
            System.out.println("作品 " + work.getWorkid() + " 处理完成");
        }

        System.out.println("getThreeYears 方法执行完毕，最终结果数量: " + resultList.size());
        return resultList;
    }
}
